import cv2
import os
from matplotlib import pyplot as plt
# from huafen import var
import numpy as np
ksize = (3,3)
sigmaX = 1
lower = 65
upper = 95
def detectEdges(img, ksize, sigmaX, lower, upper):
    res = cv2.Canny(cv2.GaussianBlur(img, ksize=ksize, sigmaX=sigmaX),lower,upper)
    return res
read_path = r'C:\Users\Admin\Desktop\imagedata\retif'
save_path = r'C:\Users\Admin\Desktop\imagedata\retif_processed'
for path in os.listdir(read_path):
    if 'png' in path:
        img_original = cv2.imread(read_path+'\\'+path,-1)
        img = cv2.cvtColor(img_original, code=cv2.COLOR_BGR2GRAY)
        edges = detectEdges(img, ksize, sigmaX, lower, upper)
        img_original[edges != 0] = [0, 0, 0]
        cv2.imwrite(save_path+'\\'+path,img_original)

# imgs = []
# edges = []
# fig = plt.figure()
# for i in range(1,13):
#     img_copy = img.copy()
#     fig.add_subplot(3,4,i)
#     imgs.append(cv2.GaussianBlur(img, ksize=(3,3), sigmaX=i/10))
#     edges.append(cv2.Canny(imgs[i-1],20+i*5,50+i*5))
#     img_copy[edges[i-1]!=0] = 0
#     plt.imshow(img_copy, cmap='gray')
#     plt.title(f'min = {20+i*5}, max = {50+i*5}')
#     plt.xticks([]), plt.yticks([])
# start = 0
# end = (351,471)
# for x in range(start,end[0]+1):
#     for y in range(start, end[1]+1):
#         out = edges[x:x+9,y:y+9]
#         print(out)
#         in_m = edges[x+2:x+7,y+2:y+7]
#         #print(in_m)
#         avg_center = np.mean(in_m)
#         avg_around = (np.sum(out)-np.sum(in_m))/(81-25)
#         if avg_around-avg_center > 4.5:
#
#             l = out.reshape(-1).tolist()
#             for i in range(20, 45):
#                 l.pop(i)
#             if var(l)>0:
#                 edges[x,y] = 0

# plt.subplot(122),plt.imshow(edges,cmap = 'gray')
# plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

#plt.show()